import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import { UserState } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
      meta: { allowVisitor: true },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/LoginView.vue'),
      meta: {
        allowVisitor: true,
        hiddenHeader: true,
      },
    },
    {
      path: '/personal-center',
      name: 'personal-center',
      component: () => import('@/views/PersonalCenter.vue'),
    },
    {
      path: '/record',
      name: 'record',
      component: () => import('@/views/AccessRecord.vue'),
    },
    {
      path: '/guide',
      name: 'guide',
      component: () => import('@/views/AccessGuide.vue'),
    },
    {
      path: '/message',
      name: 'message',
      component: () => import('@/views/MessageView.vue'),
    },
    {
      path: '/manage',
      name: 'manage-layout',
      component: () => import('@/layout/ManageLayout.vue'),
      children: [
        {
          path: '',
          name: 'manage-home',
          component: () => import('@/views/manage/ManageHome.vue'),
        },
        {
          path: 'user',
          name: 'user-management',
          component: () => import('@/views/manage/UserManagement.vue'),
        },
        {
          path: 'license-plate',
          name: 'license-plate-management',
          component: () => import('@/views/manage/LicensePlateManagement.vue'),
        },
        {
          path: 'equipment',
          name: 'equipment-management',
          component: () => import('@/views/manage/EquipmentManagement.vue'),
        },
        {
          path: 'notification',
          name: 'notification-center',
          component: () => import('@/views/manage/NotificationCenter.vue'),
        },
        {
          path: 'record',
          name: 'admin-access-record',
          component: () => import('@/views/manage/AccessRecord.vue'),
        },
        {
          path: 'personal',
          name: 'admin-personal',
          component: () => import('@/views/manage/AdminPersonel.vue'),
        },
      ],
    },
  ],
})

// 全局前置守卫：检查登录状态
router.beforeEach((to, from, next) => {
  console.log(to.fullPath)

  const userState = UserState()

  // 拦截普通用户访问管理员页面
  if (to.path.startsWith('manage') && userState.role != 0) {
    console.log('非管理员用户访问管理员页面')
    next({ name: 'home' })
  }

  // 只做简单的登录校验, 不会判断token是否有效
  if (!to.meta.allowVisitor && userState.uid === 0) {
    console.log('未登录')

    // 记住用户想去的页面（用于登录后跳转）
    next({
      name: 'login',
      query: { redirect: to.fullPath }, // 保存目标路径
    })
  } else {
    next()
  }
})

export default router
